package com.zhoutao.blog.seven.pages;

import com.zhoutao.blog.seven.model.PageList;
import com.zhoutao.blog.seven.model.detail.ArticleDetail;
import com.zhoutao.blog.seven.model.response.Comment;
import com.zhoutao.blog.seven.service.ArticleService;
import com.zhoutao.blog.seven.service.CommonService;
import com.zhoutao.blog.seven.service.query.ArticleQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Controller
@RequiredArgsConstructor
public class BlogPageController extends AbstractPageController {

    private final ArticleService articleService;

    private final CommonService commonService;


    @GetMapping("/blog")
    public String blog(Model model,
                       @RequestParam(defaultValue = "", required = false) String tag,
                       @RequestParam(defaultValue = "", required = false) String category,
                       @RequestParam(defaultValue = "1", required = false) Integer page,
                       @RequestParam(defaultValue = "5", required = false) Integer limit) {
        packageBaseInfo(model);

        // 上一页地址
        final PageList<ArticleDetail> pageList = articleService.find(ArticleQuery.of(tag, category), page, limit);
        String pre = String.format("/blog?tag=%s&category=%s&page=%s", tag, category, page - 1);
        String next = String.format("/blog?tag=%s&category=%s&page=%s", tag, category, page + 1);
        // 下一页地址
        pageList.setPrePage(pre).setNextPage(next);
        model.addAttribute("articlePage", pageList);
        model.addAttribute("tag", tag);
        model.addAttribute("category", category);
        return "blog";
    }


    @GetMapping("/blog/{blogId}")
    public String blog(@PathVariable Long blogId, Model model) {
        packageBaseInfo(model);
        final ArticleDetail detail = articleService.findById(blogId);
        final List<Comment> comments = commonService.findByBlogId(blogId);

        model.addAttribute("articleDetail", detail);
        model.addAttribute("comments", comments);
        log.info("查看文章:{}", detail.getTitle());
        return "blog/article";
    }
}